<template>
    <drag-modal  :visible="callVisible" @cancel="onCallClose" width="300px" :footer="null" :titleClass="titleClass" :mask="false">
       	<div  class="information-frame">
            <div class="information-first" v-show="XYLoginInfo.loginAccount">
                <a-icon class="btns-icon phone phone-name" type="phone" />
                <div class="phone-name">
                    {{talkState}}
                </div>
            </div>
            <div class="information-first" v-show="!XYLoginInfo.loginAccount">
                <a-icon class="btns-icon phone-lose" type="phone" theme="filled"/>
            </div>
        </div>
         <!-- 拨号盘 -->
        <div v-show="!callOpen && readyCallOpen" class="phone-frame">
			<div class="nomber-style">
				<input class="nimber-inpt" v-model="temporaryNumber" placeholder="请输入电话号码">
			</div>
			<!-- 键盘 -->
			<div class="keyboard">
                <div v-for="(item,i) in keyboard" @click="choice_number(item)" class="keyboard-number">{{item}}</div> 
			</div>
			<!-- <div class="input-list">
				<div style="height: 35px;">
                    <a-checkbox v-model="temporaryIsAutoAudio" style="color:#fff;">
                        去放电音
                    </a-checkbox>
				</div>
				<div class="input-list-nin" >
					<div >
						选择文件：
                        <a-select class="inp-style" placeholder="请选择选择音频" :value="temporaryVoiceId" @change="onVoiceChange" size="small" :dropdownMenuStyle="{fontSize:'0.8rem;'}">
                            <a-select-option :label="item.title" v-for="(item, index) in voiceSelectData" :key="item.key + index" :value="item.key" :title="item.title">
                                {{item.title}}
                            </a-select-option>
                        </a-select>
					</div>
					<div>
                        <a-upload
                            accept="audio/wav"
                            name="file"
                            :multiple="true"
                            :action="voiceUploadUrl"
                            :headers="uploadHeaders"
                            :show-upload-list="false"
                            :before-upload="beforeUpload"
                            @change="voiceUploadChange"
                            >
                            <span class="button-style" title="音频只支持WAV格式,特别需要注意的是播放的语音文件建议采样率最大不要超过48000HZ，16位。
                            因为设备自带声卡目前最大支持16位，48000HZ音质。
                            语音文件要使用单声道，因为只有右声道声音可以被远端手机听到。">
                                <a-icon type="plus-circle"  style="font-size:20px;color:green;"/>
                            </span>
                        </a-upload>
					</div>
				</div>
				
			</div> -->
			<div @click="onTemporaryDial" class="phone-type" >
				拨打
			</div>
		</div>
         <!-- 状态盘 -->
		<div v-show="callOpen" class="phone-frame">
			<div class="nomber-style-title">
				{{talkState}}
			</div>
			<div class="nomber-style">
				{{phoneNumber}}
			</div>
            <!-- 音频播放提示 -->
            <div v-show="playAudioWarning">
                <!-- <a-slider  :value="playAudioWarningData.currentTime" :min="0" :max="playAudioWarningData.duration" :tooltip-visible="true" />
                <div>总时长：{{playAudioWarningData.duration}}</div> -->
                <myAudio ref="myAudioOne"  @callBack="OnTalkStopAudio"></myAudio>
                <!-- <audio  ref="playAudioWarningDome" @canplay="getDuration" @timeupdate="updateTime" src="" controls="controls" hidden  style="margin: 5px; width: -moz-available; height: 30px;"></audio> -->
            </div>
             <!-- 消息提示 -->
            <!-- <div class="messageBox" >
                 <li v-for="(item, index) in callingMessageList" :key="index">
                    {{item}}
                </li>
            </div> -->
			<div class="phone-bottom-list tow-bottom">
				<div @click="onHangup" class="phone-type" style="color:red;">
					挂断
				</div>
			</div>
		</div>
        <div class="usails-softphone" id="usails-softphone">
            <div class="softphone-stream" style="display:none;">
                <audio id="remoteAudio"></audio>
                <audio id="localAudio" muted="muted"></audio>
                <video id="myringAudio" controls="controls"  type="audio/mp4" src="https://192.168.1.2:8089/static/wav/ring.mp3" muted/>
            </div>
        </div>
    </drag-modal>
</template>

<script>
import moment from "moment";
import { mapState } from "vuex";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import myAudio from '@/components/Crm/myaudio';


export default {
    components: {
        myAudio,
    },
    data () {
        return {
            titleClass: "ttc",
            callVisible: false,             //整体 弹窗显示
            keyboard: [1,2,3,4,5,6,7,8,9,'*',0,'#'],
            isAgentSuccess: false,          //坐席登录失败
            talkState:"",
            RongYingState:"",
            talkPlayAudio:"",           //通话中 播放音频地址(本地地址 默认是相对地址，修改WEB下载地址)
            readyCallOpen: false,       //打开拨号盘          
            callOpen: false,            //打开状态盘
            /*** 临时拨号 ****/
            temporaryIsAutoAudio: false,    //（临时）是否开启 播放语音
            temporaryVoiceId:null,             //（临时）音频ID
            temporaryVoiceUrl:'',           //（临时）音频地址
            temporaryAudioLocalPath:'',     //（临时）通话中 播放音频地址(本地地址 默认是相对地址，修改WEB下载地址)
            temporaryNumber:"",              //（临时）电话号码
            //------------音频----------------
            voiceUploadUrl:this.$Global.ApiBaseUrl + '/crm/callVoice/uploadVoice',
            voiceSelect:"",         //选择的值
            uploadHeaders:{},       //音频上传 请求头部
            downLoadType:1,         //下载 云端语音 到 语音盒子 类型 1.任务 2.临时拨号
            // settings: null,         //外呼配置
            phoneNumber:"",         //号码显示
            callParams: null,       //拨打参数(联系人信息)
            openBoxData: null,      //打开弹窗 额外传参（外呼任务信息） 
            localAudioMap: new Map(),       //下载语音盒子的音频 Map key:远程语音地址 value:本都语音地址
            isShowIntervention: false,      //是否显示介入按钮
            callingMessageList: [],             //拨打消息
            dateFormat: "YYYY-MM-DD HH:mm:ss", //任务时间格式
            playAudioWarning: false,         //是否显示 去电放音精度
            playAudioWarningData: {
                currentTime:0,
                duration:20
            },
            voice_pay: false,       // 语音播放
            calltimer: null,
            showTime:"",
            talkId:"",              //当前通话ID
        };
    },
    //接口调用（数据准备）
    created(){
         this.$store.dispatch("GetXYLoginInfo").then(res => {
            // this.login();
        }); 
        const token = Vue.ls.get(ACCESS_TOKEN);
        if (token) {
            this.uploadHeaders[ACCESS_TOKEN] = token; 
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
            voiceSelectData: state => state.callingBox.voiceSelectData,         //音频列表
            voiceMap: state => state.callingBox.voiceMap,                       //音频Map存储
            settings: state => state.callingBox.settings,                       //外呼设置 
            XYLoginInfo:state => state.callingBox.XYLoginInfo,                  //坐席信息 
        }),
    },
    methods:{
        moment,
        //监听拨打状态
        listenerState(RongYingCallState){
            let { talkId } = this;
            let { eventType,sessionId } = RongYingCallState;
            if(talkId == sessionId){
                this.RongYingState = eventType;
                switch(eventType){
                    case "callout": 
                        this.callOpen = true;
                        this.talkState = "呼出中";
                        break;
                    case "alerting": this.talkState = "振铃中";break;
                    case "answer": this.talkState = "接听中";break;
                    case "disconnect": 
                        this.isAgentSuccess = true;
                        this.talkState = "空闲中";
                        this.callOpen = false;
                        this.readyCallOpen = true;
                        let { openBoxData } = this;
                        this.resetCallBox();
                        //回调 
                        if(openBoxData && openBoxData.HangupCallBack){
                            setTimeout(()=>openBoxData.HangupCallBack(),5000); //刷新 页面数据
                        }
                    break;
                } 
            }
        },
        //临时拨号
        onTemporaryDial(){
            let {temporaryNumber} = this;
            let callParams = {
                mobile:temporaryNumber
            }
            this.openCallingBox(callParams,null);
        },
        onHangup(){
          
        },
        //挂断后回调
        LineHangupCallBack(){
            let {openBoxData} = this;
            //回调 
            if(openBoxData && openBoxData.HangupCallBack){
                setTimeout(()=>openBoxData.HangupCallBack(),2000); //刷新 页面数据
            }
        },
        //拨号
        Ctibar_invite(callParams){
            let {userInfo} = this;
            let _this = this;
            let {mobile,id,linkManId} = callParams;
            //业务类型：callTask 外呼任务；callLinkMan 直呼联系人；temporary：临时拨打
            let businessType = "temporary";
            if(id){
                businessType = "callTask";
            }else if(linkManId){
                businessType = "callLinkMan";
            }
            let callMode = {
                businessType,                           //业务类型：callTask 外呼任务；callLinkMan 直呼联系人；temporary：临时拨打
                businessJson:JSON.stringify(callParams),//业务JSON串
                callee:mobile,                          //被叫号码
            }

            this.$store.dispatch("Call",callMode).then(res => {
                if(res){
                    let { flag ,sessionId,msg} = res;
                    if(flag == 200){
                        this.talkId = sessionId;
                        this.talkState = "呼出中";
                        this.RongYingState = "callout";
                        this.phoneNumber = mobile;
                        this.callOpen = true;
                    }else{
                        this.resetCallBox();
                        this.$message.warning(msg);
                        
                    }
                }else{
                    // this.$message.warning("功能未开通 或者 话费不足");
                }
            }); 
        },  
        // Ctibar
        timer(){
            let durtime = 0;
            /**
             * 计时
             */
            this.calltimer = setInterval(function () {
                durtime = durtime + 1;
                let sec = durtime % 60;
                if (sec < 10) {
                    sec = "0" + sec;
                }
                let min = Math.floor((durtime % (60 * 60)) / 60);
                if (min < 10) {
                    min = "0" + min;
                }
                let hour = Math.floor(durtime / (60 * 60));
                if (hour < 10) {
                    hour = "0" + hour;
                }
                this.showTime = hour + ":" + min + ":" + sec;
            }, 1000);
        },
        canceltimer() {
            if (this.calltimer != null) {
                clearInterval(this.calltimer);
            }
            this.showTime = "";
        },
        //校验是否可以 线路外呼
        openCallingBox(callParams,data){
            let _this = this;
            this.$store.dispatch("IsCallEnable").then(res => {
                let message = "";
                switch(res){
                    case "NoInit":message="功能未开通";break;
                    case "Disable":message="功能被停用";break;
                    case "NoMinutes":message="话费不足，请购买话费";break;
                }
                if(message){
                    _this.$message.warning(message);
                }else{
                    _this.doCalling(callParams,data);
                }
            }); 
        },
        //打开拨号盘 
        doCalling(callParams,data){
            console.log("打开拨号盘11",data);
            let {loginAccount} = this.XYLoginInfo;
            if(!loginAccount){
                this.$message.warning("未分配坐席");
                return;
            }

            this.callParams = null;
            this.openBoxData = data;
            this.callVisible = true;
            this.isShowIntervention = false;
            this.talkPlayAudio = null;
            this.temporaryIsAutoAudio = false;
            this.temporaryVoiceId = null,
            this.temporaryVoiceUrl = '';
            this.temporaryAudioLocalPath = null;
            if(data){
                const {callType,voiceUrl,voiceId,isPlayAudio} = data;
                if(callType == 2 && voiceUrl){
                    this.temporaryIsAutoAudio = true;
                    this.temporaryVoiceUrl = voiceUrl;
                }
            }
            if(!callParams){
                this.readyCallOpen = true;
                return;
            }
            this.callParams = callParams;
            this.Ctibar_invite(callParams); 
        },
         //设置 音频播放提示的参数，并监听播放完成
        SetPlayAudioWarning(){
            const { temporaryVoiceUrl } = this;
            if(temporaryVoiceUrl){
                this.Ctibar_mute();
                this.isShowIntervention = true;
                this.playAudioWarning = true;
                let data = {
                    src: temporaryVoiceUrl,
                    volume: 50
                }
                this.$refs.myAudioOne.init(data);
            }
        },
        //通话中结束播放默认音频
        OnTalkStopAudio()
        {
            this.Ctibar_unmute();
            this.isShowIntervention = false;
        },
        onCallClose(){
            let { RongYingState } = this;
            console.log("关闭线路外呼时，拨打状态XYState：",this.RongYingState);
            if(RongYingState == "callout" || RongYingState == "alerting" || RongYingState == "answer" ){
                this.callVisible = false;
                // this.$message.warning(this.talkState +"中，不能关闭");
                // return;
            }else{
                this.resetCallBox();
            }
           
        },
        resetCallBox(){
            this.callVisible = false;
            this.callOpen = false;
            this.readyCallOpen = false;
            this.temporaryNumber = '';
            this.phoneNumber = '';
            this.callParams = null;
            // this.playAudioWarning = false;
            // this.StopPlayAudioWarning();
        },
     
        choice_number(val){
            this.temporaryNumber = this.temporaryNumber + val;
            console.log('-----',this.temporaryNumber,val)
        },
        //上传之前
        beforeUpload(file) {
            const isOK = file.type.indexOf("audio") > -1;
                // file.type === "audio/wav";
            if (!isOK) {
                this.$message.error("只能选择wav的音频!");
            }
            const isLimitSize = file.size / 1024 / 1024 < 5;
            if (!isLimitSize) {
                this.$message.error("音频不能超过5MB!");
            }
            return isOK && isLimitSize;
        },
        //上传音频
        voiceUploadChange(info){
            let status = info.file.status;
            switch(status){
                case "done":{
                    let { response } = info.file;
                    if(response.code == 200){
                        this.$message.success(info.file.name +",上传成功!");
                        this.$store.dispatch("ListVoicePage");      //获取音频列表
                        // this.voicePage();
                    }else{
                        this.$message.error(info.file.name +",上传失败!");
                    }
                };break;
                case "error":{
                    this.$message.error(info.file.name +",上传失败!");
                };break;

            }
            console.log("上传音频-->结果：",info);
        },
        //选择 音频 事件
        onVoiceChange(key){
            this.temporaryAudioLocalPath = '';
            console.log("选择 音频 事件",key)
            let voiceItem = this.voiceMap.get(key);
            if(voiceItem){
                let {id,voiceName,voiceUrl} = voiceItem;
                this.temporaryVoiceId = id;
                this.temporaryVoiceUrl = voiceUrl;
            }
        },
    },
    watch:{
      
    }
};
</script>


<style lang="less">
.nomber-style-title {
	text-align: left;
	font-size: 20px;
	width: 95%;
	margin: auto;
	margin-top: 10px;
}
.phone-bottom-list {
	width: 60%;
	margin: auto;
	display: flex;
	justify-content: space-around;
}
.phone-type {
	height: 80px;
	width: 80px;
	line-height: 80px;
	margin: auto;
	margin-top: 25px;
	border-radius: 80px;
	background-color: #fff;
	color: #41CC9D;
	cursor: pointer;
    font-size: 20px;
}


.tow-bottom {
	position: relative;
	top: 200px;
}

.nimber-inpt {
	background-color:  #2A3B42;
	border: 0;
	outline:none; 
	color: #FFFFFF;
}
.ttc{
    margin: -10px 0px -10px -20px;
}
.phone-frame {
	border: 1px solid #2A3B42;
	width: 300px;
	height: 485px;
	background-color: #2A3B42;
	color:  #fff;
	text-align: center;
	font-size: 10px;
    // margin: -24px;
    padding-bottom: 30px;
    
} 

.information-frame {
	width: 100%;
	// margin: auto;
	height: 50px;
	// margin-bottom: 24px;
	display: flex;
	justify-content: space-between;
	padding: 5px;
    font-size: 14px;
	/* background-color: #FFFFFF; */
}
	
.information-first {
	width: 4rem;
    font-size: 12px;
	// padding: 0 20px 0 10px;
}

.phone {
    font-size: 24px;
	// height: 15px;
}

.phone-name {
	color: #41CC9D;
}
.phone-lose{
    font-size: 36px;
}

.bt-color{
	color: #1890ff;;
}


.phone-txt-color {
	/* color: #000; */
	// font-size: 10px;
	white-space:nowrap;
	overflow: hidden;
}

.list-color {
	color: #7EC1FF;
}

.information-second {
	width: 120px;
	// padding: 0 0 0 10px;
}

.second-txt {
	// width: 100px;
	text-align: left !important;
}

.information-third {
	display: flex;
	padding-right: 10px;
	overflow: hidden;
}
.third-box {
	padding: 0 10px 0 0;
    cursor: pointer;
    font-size: 12px;
}

.nomber-style {
	width: 80%;
	margin:auto;
	text-align: left;
	font-size: 14px;
	margin-top: 20px;
	border-bottom: 1px solid #536065;
	white-space:nowrap;
	overflow: hidden;
	padding: 0 0 5px 0;
    font-size: 24px;
}

.keyboard {
	width: 80%;
	margin: auto;
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
	margin-top: 10px;
	border-bottom: 1px solid #536065;
	padding: 0 0 5px 0;
    font-size: 24px;
}

.keyboard-number {
	width: 60px;
    height: 50px;
    line-height: 50px;
	text-align: center;
    cursor: pointer;
	/* padding: 0 0 0 10px; */
}

.input-list {
	width: 80%;
	margin: auto;
	text-align: left !important; 
	margin-top: 15px;
}
.inp-style {
	width: 120px;
    
}

.input-list-nin{
	margin-left: 5px;
	display: flex;
	justify-content: space-between;
}

.button-style{
	padding: 0 0 0 5px;
    color: #fff;
}
.nimber-inpt {
	background-color:  #2A3B42;
	border: 0;
	outline:none; 
	color: #FFFFFF;
    width: 100%;
    font-size: 24px;
}
</style>

<style lang="less" scoped>
.messageBox{
    height: 250px;
    width: 100%;
    overflow: auto;
    text-align: left;
    padding: 0 30px;
}
// .messageBox::-webkit-scrollbar{
//         display: none;
// }
/deep/.ant-modal-header{
    padding: 10px 24px !important;
    background: #c0c0c0 !important;
    border-bottom: 0px solid #a0a0a0 !important;
}
/deep/.ant-modal-close-x {
  height: 21px !important;
  line-height: 18px !important;
  width: 30px !important;
}
// /deep/.ant-modal-mask{
//     display: none !important;
// }
/deep/.ant-modal-body{
    padding: 0px !important;
}
/deep/.ant-select-sm .ant-select-selection__rendered{
    line-height: 22px !important;
}
.ant-radio-group, .ant-checkbox-wrapper{
    font-size: 10px !important;
}
/deep/.ant-modal-footer{
    display: none !important;
}
</style>